package com.neusoft.work.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neusoft.work.dao.CustomerDao;
import com.neusoft.work.dao.MealManagementDao;
import com.neusoft.work.po.Customer;
import com.neusoft.work.po.MealManagement;
import com.neusoft.work.po.PageResponseBean;
import com.neusoft.work.po.ResponseBean;
import com.neusoft.work.service.MealManagementService;

@Service
public class MealManagementServiceImpl implements MealManagementService {
	@Autowired
    private MealManagementDao dao;
    @Autowired
    private CustomerDao customerDao;

    @Override
    public ResponseBean<Integer> addMealManagement(MealManagement m) {
        int rows = dao.insert(m);
        return rows>0
            ? new ResponseBean<>(m.getId())
            : new ResponseBean<>(500,"添加失败");
    }

    @Override
    public ResponseBean<Integer> updateMealManagement(MealManagement m) {
        int rows = dao.updateById(m);
        return rows>0
            ? new ResponseBean<>(m.getId())
            : new ResponseBean<>(500,"更新失败");
    }

    @Override
    public ResponseBean<Integer> deleteMealManagement(Integer id) {
        int rows = dao.deleteById(id);
        return rows>0
            ? new ResponseBean<>(rows)
            : new ResponseBean<>(500,"删除失败");
    }

    @Override
    public PageResponseBean<List<MealManagement>> queryMealManagementByName(String name, Long cur, Long number) {
        Page<MealManagement> page = new Page<>(cur, number);
        QueryWrapper<MealManagement> qw = new QueryWrapper<>();
        if (name!=null && !name.trim().isEmpty()) {
            // 先根据名字查 customerId
            List<Integer> ids = customerDao
                .selectList(new QueryWrapper<Customer>().like("name", name).select("id"))
                .stream().map(Customer::getId).toList();
            if (ids.isEmpty()) {
                return new PageResponseBean<>(500,"无数据");
            }
            qw.in("customer_id", ids);
        }
        IPage<MealManagement> p = dao.selectPage(page, qw);
        List<MealManagement> list = p.getRecords();
        long tot = p.getTotal();
        PageResponseBean<List<MealManagement>> rb = new PageResponseBean<>(list);
        rb.setTotal(tot);
        return rb;
    }


}
